package net.wantongtech.xa.uploadbasicinfo.service;

import com.wtkj.vo.dzzf.base.kfwd.Account;
import com.wtkj.vo.dzzf.base.qxsjz.entity.DisputeTransOut;
import com.wtkj.vo.dzzf.base.qxsjz.entity.PortalTransOut;
import com.wtkj.zwxt.stat.TradeStaticValue;
import lombok.extern.slf4j.Slf4j;
import net.wantongtech.xa.uploadbasicinfo.dao.RecoverDisputeTransDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author MaShibo
 * 2021/2/9 0009
 */
@Slf4j
@Service
public class RecoverDisputeTransService {

    @Resource
    private RecoverDisputeTransDao recoverDisputeTransDao;

    public void process() {
        List<DisputeTransOut> disputeTransOutList = recoverDisputeTransDao.queryAllDisputeTarnsOut();

        try {
            TimeUnit.MINUTES.sleep(2);
        } catch (InterruptedException e) {
            log.error(e.getMessage());
            Thread.currentThread().interrupt();
        }

        log.info("共查询到{}条争议交易数据", disputeTransOutList.size());
        if (disputeTransOutList.isEmpty()) {
            return;
        }

        for (DisputeTransOut disputeTransOut : disputeTransOutList) {
            processDisputeEntry(disputeTransOut);
        }

        log.info("处理完成");
    }

    private void processDisputeEntry(DisputeTransOut disputeTransOut) {
        String transactionId = disputeTransOut.getTransactionId();
        log.info("开始处理原始交易：{}", transactionId);

        log.info("恢复争议表数据...");
        recoverDisputeTransDao.recoverDisputeTransOut(transactionId);

        Integer dealFlag = disputeTransOut.getDealFlag();
        if (dealFlag != TradeStaticValue.DsptStatus.ACCOUNT) {
            log.info("非争议支付状态...");
            return;
        }


        PortalTransOut portalTransOut = recoverDisputeTransDao.queryPortalTransOutById(transactionId);

        String accountId = portalTransOut.getAccountId();
        Long fee = portalTransOut.getFee();

        if (StringUtils.isBlank(accountId)) {
            log.info("原始交易中accountId不存在");
            return;
        }

        Account account = recoverDisputeTransDao.queryAccountById(accountId);

        if (account == null) {
            log.info("对应账户信息不存在");
            return;
        }

        if (recoverDisputeTransDao.deleteAccountConsume(accountId, transactionId) == 1) {
            log.info("删除ac_accountconsume表数据成功");
        } else {
            log.info("删除ac_accountconsume表数据失败");
        }


        log.info("恢复账户金额...");
        account.setAccountBalance(account.getAccountBalance().add(BigDecimal.valueOf(fee)));
        recoverDisputeTransDao.updateObject(account);


        log.info("恢复原始交易数据...");
        recoverDisputeTransDao.recoverPortalTransOut(transactionId);


        log.info("删除合并交易表数据...");
        recoverDisputeTransDao.deleteIntegratedTransOut(transactionId);
    }
}
